package cn.zzq.shop.common.util;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component("redisUtil")
public class RedisUtil
{
	@Resource
	private RedisTemplate redisTemplate;
	/**
	 * 往redis中设置键值对
	 */
	public boolean set(String key,String value){
		
		return (boolean) this.redisTemplate.execute(new RedisCallback()
		{
			@Override
			public Object doInRedis(RedisConnection connection) throws DataAccessException
			{
				byte[] keyBytes = redisTemplate.getStringSerializer().serialize(key);
				byte[] valueBytes = redisTemplate.getStringSerializer().serialize(value);
				connection.set(keyBytes, valueBytes);
				return true;
			}
		});
	}
	
	/**
	 * 往redis中设置键值对，设置键保存时间秒数
	 */
	public boolean set(String key,String value,int timeOut){
		
		return (boolean) this.redisTemplate.execute(new RedisCallback()
		{
			@Override
			public Object doInRedis(RedisConnection connection) throws DataAccessException
			{
				byte[] keyBytes = redisTemplate.getStringSerializer().serialize(key);
				byte[] valueBytes = redisTemplate.getStringSerializer().serialize(value);
				connection.set(keyBytes, valueBytes);
				//设置保存时间
				return connection.expire(keyBytes, timeOut);
			}
		});
	}
	
	/**
	 * 往redis中设置键值对,设置键保存时间date类型
	 */
	public boolean set(String key,String value,Date timeOut){
		
		return (boolean) this.redisTemplate.execute(new RedisCallback()
		{
			@Override
			public Object doInRedis(RedisConnection connection) throws DataAccessException
			{
				byte[] keyBytes = redisTemplate.getStringSerializer().serialize(key);
				byte[] valueBytes = redisTemplate.getStringSerializer().serialize(value);
				connection.set(keyBytes, valueBytes);
				//设置保存时间
				return connection.expire(keyBytes, timeOut.getTime());
			}
		});
	}
	
	/**
	 * 获取值
	 */
	public String get(String key){
		return "" + this.redisTemplate.execute(new RedisCallback()
		{
			@Override
			public Object doInRedis(RedisConnection connection) throws DataAccessException
			{
				byte[] keyBytes = redisTemplate.getStringSerializer().serialize(key);
				byte[] valueBytes = connection.get(keyBytes);
				/*讲字符数组转换成字符串*/
				String value = redisTemplate.getStringSerializer().deserialize(valueBytes) + "";
				return value;
			}		
		});
	}
	
	/**
	 * 删除值
	 */
	public String delete(String key){
		return "" + this.redisTemplate.execute(new RedisCallback()
		{
			@Override
			public Object doInRedis(RedisConnection connection) throws DataAccessException
			{
				byte[] keyBytes = redisTemplate.getStringSerializer().serialize(key);
				return connection.del(keyBytes);
			}		
		});
	}
}
